# -*- coding:utf-8 -*-
from django.shortcuts import render
from libs.base.baseview import BaseView
from models import User
from django.db.models import Q
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from rest_framework import authentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler
from django.contrib.auth.models import Group,Permission
from serializers import UserDetailSerializer, UserRegSerializer, GroupSerializer, PermissionSerializer, GroupCreateSerializer
from permissions import IsOwnerOrReadOnly


class UserViewset(BaseView):
    '''
        create:
        创建用户
        retrieve：

    '''
    queryset = User.objects.all()
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)
    def get_serializer_class(self):
        if self.action == "retrieve":
            return UserDetailSerializer
        elif self.action == "create":
            return UserRegSerializer

        return UserDetailSerializer

    def get_permissions(self):
        if self.action == "retrieve":
            return [permissions.IsAuthenticated()]
        elif self.action == "create":
            return []

        return []

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def get_object(self):
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()



class GroupViewset(BaseView):
    queryset = Group.objects.all()
    # permissions = [permissions.IsAuthenticated,IsOwnerOrReadOnly]
    def get_serializer_class(self):
        if self.action == 'create':
            return GroupCreateSerializer
        return GroupSerializer


class PermissionViewset(BaseView):
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    # permissions = [permissions.IsAuthenticated, IsOwnerOrReadOnly]